package com.uinnova.product.eam.web.asset.mvc;

import com.alibaba.fastjson.JSONObject;
import com.binary.core.io.support.FileResource;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.util.ControllerUtils;
import com.binary.json.JSON;
import com.binary.framework.web.RemoteResult;
import com.uinnova.product.eam.base.model.AttrConfInfo;
import com.uinnova.product.eam.base.model.AttrDefInfo;
import com.uinnova.product.eam.base.model.FileResourceMeta;
import com.uinnova.product.eam.config.Env;
import com.uinnova.product.eam.model.asset.ArchitecturalResolutionDTO;
import com.uinnova.product.eam.service.utils.ZipFileUtils;
import com.uinnova.product.eam.web.asset.bean.ArchitecturalNameCheckVo;
import com.uinnova.product.eam.web.asset.bean.ArchitecturalResolutionVO;
import com.uinnova.product.eam.web.asset.bean.ArchitecturalVo;
import com.uinnova.product.eam.web.asset.bean.SearchArchitecturalVo;
import com.uinnova.product.eam.web.asset.peer.ArchitecturalPeer;
import com.uinnova.product.eam.web.util.ControllerResourceUtil;
import com.uinnova.product.vmdb.comm.model.ci.CCcCiClass;
import com.uinnova.product.vmdb.comm.model.ci.CcCiAttrDef;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiClassInfo;
import com.uino.api.client.cmdb.ICIClassApiSvc;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 架构决议管理
 */
@RestController
@RequestMapping("/asset/architectural")
public class ArchitecturalResolutionMVC {

    @Resource
    private ICIClassApiSvc iciClassApiSvc;

    @Resource
    private ArchitecturalPeer architecturalPeer;


    /**
     * 创建或保存架构决议信息
     * @param body
     * @return
     */
    @PostMapping("createArchitectural")
    public RemoteResult createArchitecturalResolution(@RequestBody String body) throws ValidationException {
        ArchitecturalVo architecturalVo = JSON.toObject(body, ArchitecturalVo.class);
        for (ArchitecturalResolutionVO architecturalResolutionVO : architecturalVo.getInfos()) {
            if (architecturalResolutionVO.getClassId() == null) {
                architecturalResolutionVO.setClassId(getCiClassIdByName(Env.ARCH_RESOLUTION.getClassName()));
            }
        }
        ArchitecturalNameCheckVo architecturalNameCheckVo = new ArchitecturalNameCheckVo();
        architecturalNameCheckVo.setCiId(architecturalVo.getInfos().get(0).getId());
        architecturalNameCheckVo.setName(architecturalVo.getInfos().get(0).getAttrs().get(Env.ARCH_RESOLUTION.getResolutionName()));
        architecturalNameCheckVo.setSubSysCode(architecturalVo.getInfos().get(0).getAttrs().get(Env.ARCH_RESOLUTION.getSubsystemCode()));
        boolean hasName = architecturalPeer.checkArchitecturalName(architecturalNameCheckVo);
        if (hasName) {
            throw new ValidationException("名称已存在");
        }
        Long result = architecturalPeer.createArchitecturalResolution(architecturalVo);
        return new RemoteResult(result);
    }

    /**
     * 获取架构决议枚举的属性定义
     *
     * @return
     */
    @GetMapping("/getSubsystemAttrDefs")
    public RemoteResult getSubsystemAttrDefs() {
        Long subSystemCiClassId = getCiClassIdByName(Env.ARCH_RESOLUTION.getClassName());
        CcCiClassInfo ccCiClassInfo = iciClassApiSvc.queryClassInfoById(subSystemCiClassId);
        List<CcCiAttrDef> attrDefs = ccCiClassInfo.getAttrDefs();
        List<CcCiAttrDef> collect = attrDefs.stream()
                .filter(attrDef -> attrDef.getProType() == 6).collect(Collectors.toList());
        return new RemoteResult(collect);
    }

    @GetMapping("/getArchitecturalAttr")
    public void selectAttrConf(HttpServletRequest request, HttpServletResponse response) {
        AttrConfInfo attrConfInfo = JSONObject.parseObject(Env.ARCH_RESOLUTION.getPageConfig(), AttrConfInfo.class);
        AttrDefInfo attrDefInfo = architecturalPeer.selectAttrConf(attrConfInfo);
        ControllerUtils.returnJson(request, response, attrDefInfo);

    }

    /**
     * 根据子系统的ciCode获取架构决议信息
     *
     * @param body
     * @return
     */
    @PostMapping("/getInfoBySubsystemCode")
    public RemoteResult getInfoBySubsystemCode(@RequestBody String body) {
        ArchitecturalResolutionVO architecturalResolutionVO = JSON.toObject(body, ArchitecturalResolutionVO.class);
        architecturalResolutionVO.setClassId(getCiClassIdByName(Env.ARCH_RESOLUTION.getClassName()));
        return new RemoteResult(architecturalPeer.getInfoBySubsystemCode(architecturalResolutionVO));
    }

    @GetMapping("/getInfoByCiId")
    public RemoteResult getInfoByCiId(@RequestParam("ciId") Long ciId){
        BinaryUtils.checkEmpty(ciId, "ciId");
        return new RemoteResult(architecturalPeer.getInfoByCiId(ciId));
    }


    /**
     * 根据分类名称获取分类id
     *
     * @param className
     * @return
     */
    private Long getCiClassIdByName(String className){
        CCcCiClass cdt = new CCcCiClass();
        cdt.setClassNameEqual(className);
        return iciClassApiSvc.queryClassByCdt(cdt).get(0).getCiClass().getId();
    }

    @PostMapping("/getArchitecturalById")
    public RemoteResult getArchitecturalById(@RequestBody SearchArchitecturalVo searchArchitecturalVo){
        BinaryUtils.checkEmpty(searchArchitecturalVo.getId(), "id");
        return new RemoteResult(architecturalPeer.getArchitecturalById(searchArchitecturalVo));
    }

    @GetMapping("/downloadByArchitecturalId/{architecturalId}")
    public void downloadByArchitecturalId(HttpServletRequest request, HttpServletResponse response,@PathVariable("architecturalId") Long architecturalId){
        List<Long> resIds = architecturalPeer.getResIdsById(architecturalId);
        List<FileResourceMeta> fileResources = architecturalPeer.download(resIds);
        ArchitecturalResolutionDTO architecturalResolutionDTO = architecturalPeer.getInfoByCiId(architecturalId);
        FileResource fileResource = ZipFileUtils.zipToResource(fileResources,architecturalResolutionDTO.getAttrs().get("决议名称")+".zip");
        ControllerResourceUtil.returnResource(request, response, fileResource, null,
                false, fileResource.getName());
    }

    @PostMapping("/changeSubsystemCode")
    public void changeSubsystemCode(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "sourceCode")String sourceCode,
                                    @RequestParam(value="targetCode")String targetCode) {
        BinaryUtils.checkEmpty(sourceCode, "sourceCode");
        BinaryUtils.checkEmpty(targetCode, "targetCode");
        List<Long> ids = architecturalPeer.changeSubsystemCode(sourceCode,targetCode,getCiClassIdByName(Env.ARCH_RESOLUTION.getClassName()));
        ControllerUtils.returnJson(request, response, ids);
    }


}
